/**
 */
(function($)
{
	function init(target)
	{
		var text = [];
		text.push('<div tabindex="-1"  class="selectMenu">');
		/* text.push('<div class="clearDiv" style="clear: both;"></div>'); */
		text.push('</div>');
		var selectMenu = $(text.join('')).insertAfter(target);

		selectMenu.hide();
		$(target).hide().appendTo(selectMenu);
		return {
			selectMenu : selectMenu
		};
	};
	function initSearchData(target)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var data = opts.data;

		var searchData = [];
		for (var i in data)
		{
			var itemString = [];
			var itemDat = data[i];
			for (var m in itemDat)
			{
				itemString.push(itemDat[m]);
			}
			searchData.push(itemString.join(""));
		}
		state.searchData = searchData;
	};

	function bindEvents(target)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var doc = state.doc;
		var searchedData = state.searchedData;

		var selectMenu = doc.selectMenu;

		$(document).unbind('.selectMenu').bind('mousedown.selectMenu',
				function(e)
				{
					var m = $(e.target).closest('div.selectMenu');
					if (m.length)
					{
						// alert("target==m[0]");
						if (selectMenu[0] == m[0])
						{
							return;
						}
					}
					hide(target);
				});

		selectMenu.delegate(".selectItem", "mouseenter", function(e)
				{
					selectMenu.find("div.selectItem")
							.removeClass("selectItem-active");
					$(this).addClass("selectItem-active");
				});
		selectMenu.delegate(".selectItem", "click", function(e)
		{
			/*
			 * var item = $(this); var index = item.attr("index");
			 */

			var activeData = getActive(target);

			var itemData = activeData.itemData;
			var finalText = activeData.finalText;
			if (opts.beforeClickItem.call(target, itemData) == false)
				return;
		
			if (state.beforeClick)
			{
				if (state.beforeClick.call(target, itemData, finalText) == false)
					return;
			}
			hide(target);
			selectMenu.find("div.selectItem").remove();

				// onClickItem.call(target, data[index])
				/** ************************************** */
				/*
				 * show(target); for (var i = 0; i < 10; i++) {
				 * selectMenu.append('<div class="selectItem">asdfasdf</div>'); }
				 */
		});
		selectMenu.hover(function()
				{
					state.onHover = true;
				}, function()
				{
					state.onHover = false;
				});
	}

	/*
	 */
	function search(target, val)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var matchList = opts.matchList;
		var data = opts.data;
		var doc = state.doc;
		var selectMenu = doc.selectMenu;

		var searchedList = [];

		var firstMatch = [];
		var indexMatch = [];

		if (val != "" && val != null && val != undefined)
		{
			val=val.toLowerCase();
			for (var m in data)
			{
				var itemData = data[m];
				var isMatch = false;
				for (var i in matchList)
				{
					var testString = itemData[matchList[i]];
					if (testString)
					{
						if (testString.indexOf(val) == 0)
						{
							firstMatch.push(itemData);
							isMatch = false;
							break;
						};
						if (testString.indexOf(val) > 0)
						{
							isMatch = true;
							
						};
					}
				}
				if (isMatch)
				{
				  indexMatch.push(itemData);
				}
			}
		}

		selectMenu.find("div.selectItem").remove();
		
		/**
		 * ********/
		firstMatch.sort(orderBy("name"));
		
		indexMatch.sort(orderBy("name"));

		searchedList = firstMatch.concat(indexMatch);
	
//		alert(firstMatch.length+ " "+indexMatch.length+"  "+searchedList.length );
		
//		$("#showAlert2").val(indexMatch.length + "   " + firstMatch.length);
	
		state.searchVal = val;
		state.searchedData = searchedList;

		if (state.searchedData == 0)
		{
			hide(target);
		}

		function orderBy(index)
		{
			return function(o, p)
			{
				var a, b;
				if (typeof o === "object" && typeof p === "object" && o && p)
				{
					
					a = o[index];
					b = p[index];
					
			/*		alert(a);*/
					
					if (a === b)
					{
						return 0;
					}
					if (typeof a === typeof b)
					{
						return a < b ? -1 : 1;
					}
					return typeof a < typeof b ? -1 : 1;
				} else
				{
					throw ("error");
				}
			}
		}
	}
	/*
	 * 
	 * activeData : searchedData[index], finalText : finalText
	 */
	function getActive(target)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var searchedData = state.searchedData;
		var matchList = state.options.matchList;
		var doc = state.doc;

		var selectMenu = doc.selectMenu;

		var active = selectMenu.find("div.selectItem-active");
		var index = active.attr("index");

		var finalText = opts.formatter.call(target, searchedData[index],
				matchList);
		return {
			itemData : searchedData[index],
			finalText : finalText
		}

	}
	function isActive(target)
	{
		var state = $.data(target, 'selectMenu');
		return state.isActive;
	}

	function nextItem(target)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var doc = state.doc;
		var data = opts.data;
		var selectMenu = doc.selectMenu;

		var active = selectMenu.find("div.selectItem-active");
		var next = active.next("div.selectItem");

		if (next.length == 0)
		{
			next = selectMenu.find("div.selectItem:first");
		}
		if (next.length)
		{
			active.removeClass("selectItem-active");
			next.addClass("selectItem-active");
		}
	}
	function prevItem(target)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var doc = state.doc;
		var data = opts.data;
		var selectMenu = doc.selectMenu;

		var active = selectMenu.find("div.selectItem-active");

		var prev = active.prev("div.selectItem");
		if (prev.length == 0)
		{
			prev = selectMenu.find("div.selectItem:last");
		}
		if (prev.length)
		{
			active.removeClass("selectItem-active");
			prev.addClass("selectItem-active");
		}

	}
	function select(target)
	{

	}

	function show(target, site)
	{
		var state = $.data(target, 'selectMenu');
		var searchedData = state.searchedData;
		var searchVal = state.searchVal;
		var opts = state.options;
		var maxShow = opts.maxShow;
		var matchList = opts.matchList;
		var doc = state.doc;
		var selectMenu = doc.selectMenu;

		if (searchedData == null || searchedData.length == 0)
			return;

		/*
		 * var itemList=[]; for (var n in searchedData) { var cs = ""; if (n ==
		 * 0) cs = "selectItem-active" selectMenu.append('<div
		 * class="selectItem ' + cs + '" index="' + n+ '"><span>' +
		 * searchedData[n].email + '</span></div>');
		 * opts.formatterItem.call(target,); }
		 */
		selectMenu.append(opts.formatterItem.call(target, searchedData,
				matchList, searchVal, maxShow));

		if (site)
		{
			selectMenu.css(site);
		}
		state.isActive = true;
		selectMenu.show();
	}

	function hide(target)
	{
		var state = $.data(target, 'selectMenu');
		var opts = state.options;
		var doc = state.doc;

		var selectMenu = doc.selectMenu;

		state.onHover = false;
		state.isActive = false;
		selectMenu.hide();
	}
	$.fn.selectMenu = function(options, param)
	{
		if (typeof options == 'string')
		{
			return $.fn.selectMenu.methods[options](this, param);
		}
		options = options || {};
		return this.each(function()
				{
					var state = $.data(this, 'selectMenu');
					if (state)
					{
						$.extend(state.options, options);
					} else
					{
						var doc = init(this);
						state = $.data(this, 'selectMenu', {
									doc : doc,
									options : $.extend({},
											$.fn.selectMenu.defaults, options)
								});
						initSearchData(this);
						bindEvents(this);
					}
				});
	}
	$.fn.selectMenu.methods = {
		show : function(jqDom, site)
		{
			return show(jqDom[0], site);
		},
		hide : function(jqDom)
		{
			return search(jqDom[0]);
		},
		search : function(jqDom, val)
		{
			return search(jqDom[0], val);
		},
		nextItem : function(jqDom)
		{
			return nextItem(jqDom[0]);
		},
		prevItem : function(jqDom)
		{
			return prevItem(jqDom[0]);
		},
		isActive : function(jqDom)
		{
			return isActive(jqDom[0]);
		},
		getActive : function(jqDom)
		{
			return getActive(jqDom[0]);
		}
	};
	$.fn.selectMenu.defaults = {
		data : "",
		matchList:null, 
		maxShow : 10,
/*		onSelect : function()
		{
		},*/
		beforeClickItem : function()
		{
		},
		formatter : function(activeData, matchList)
		{
			if (!activeData)
				return;
			var st = [];
			for (var m in matchList)
			{
				var ss = activeData[matchList[m]];
				if (ss)
				{
					st.push(ss);
				}
			}
			return st.join("");
		},
		formatterItem : function(searchedData, matchList, val, maxShow)
		{
			var selectMenu = [];
			for (var n in searchedData)
			{
				if (n > maxShow)
					break;
				var itemData = searchedData[n];
				var cs = "";
				if (n == 0)
					cs = "selectItem-active";
				selectMenu.push('<div class="selectItem  ' + cs + '" index="'
						+ n + '"><span>');
				for (var m in matchList)
				{
					var pData = itemData[matchList[m]];
					if (pData)
					{
						selectMenu.push('' + pData + '')
					}
				}
				selectMenu.push('</span></div>');
			}
			return selectMenu.join("");
		}
	}
})(jQuery);
